package com.web.kdl.controller.user;


import com.web.kdl.common.result.CommonResult;
import com.web.kdl.common.result.MessageConstants;
import com.web.kdl.common.result.ReturnCode;
import com.web.kdl.config.EmailConfig;
import com.web.kdl.config.security.components.AuthUser;
import com.web.kdl.daoV2.auth.PermissionDao;
import com.web.kdl.entity.user.UserInfo;
import com.web.kdl.pojo.Vo.UserVo;
import com.web.kdl.pojo.form.*;
import com.web.kdl.service.email.IEmailService;
import com.web.kdl.service.user.UserService;
import com.web.kdl.util.PasswordGenerator;
import com.web.kdl.util.UserValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;


@Controller
@ResponseBody
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    TemplateEngine templateEngine;

    @Autowired
    IEmailService emailService;

    @Autowired
    PermissionDao permissionDao;

    @Autowired
    EmailConfig emailConfig;

    @Resource
    PasswordEncoder passwordEncoder;
//   用户注册（添加用户）
    @PostMapping("/addUser")
    public CommonResult addUser(@RequestBody UserAddForm form) {
        // 1. 参数校验
        if (StringUtils.isEmpty(form.getUsername())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(),"用户名不能为空");
        }
        if (StringUtils.isEmpty(form.getPassword())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(),"密码不能为空");
        }
        if (StringUtils.isEmpty(form.getPasswordConfirm())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(),"二次确认密码不能为空");
        }
        String validateUsername = UserValidationUtil.validateUsername(form.getUsername());
        if (validateUsername!=null){
           return CommonResult.error(ReturnCode.FAIL.getCode(),validateUsername);
        }
        String validatePassword = UserValidationUtil.validatePassword(form.getPassword());
        if (validatePassword!=null){
            return CommonResult.error(ReturnCode.FAIL.getCode(),validatePassword);
        }
//       邮箱格式判断
        if (!StringUtils.isEmpty(form.getEmail()) && !UserValidationUtil.validateEmail(form.getEmail())) {}

//      数据校验 密码两次输入是否一致
        if (!form.getPassword().equals(form.getPasswordConfirm())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(), MessageConstants.USER_NOT_FOUND);
        }
//      用户是否存在校验
        if (userService.findByUsername(form.getUsername()) != null) {
            return CommonResult.error(ReturnCode.FAIL.getCode(), MessageConstants.USER_ALREADY_EXISTS);
        }
//      注册逻辑
        Boolean result= userService.addUser(form);
        return result?CommonResult.success(MessageConstants.USER_CREATED_SUCCESSFULLY):
        CommonResult.error(ReturnCode.FAIL.getCode(), MessageConstants.USER_ALREADY_EXISTS);
    }

    /**
     * 登录接口（实际认证由LoginFilter处理）
     * 保留参数校验，但移除认证逻辑
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody UserForm form) {
        // 1. 参数校验
        if (StringUtils.isEmpty(form.getUsername())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(),"用户名不能为空");
        }
        if (StringUtils.isEmpty(form.getPassword())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(),"密码不能为空");
        }
        String validateUsername = UserValidationUtil.validateUsername(form.getUsername());
        if (validateUsername!=null){
            return CommonResult.error(ReturnCode.FAIL.getCode(),validateUsername);
        }
        String validatePassword = UserValidationUtil.validatePassword(form.getPassword());
        if (validatePassword!=null){
            return CommonResult.error(ReturnCode.FAIL.getCode(),validatePassword);
        }
//      登录逻辑
        return userService.login(form);
    }

    //查询所有用户
    @PostMapping("/getAllUser")
    public CommonResult getAllUser(){
        List<UserVo> allUser = userService.getAllUser();
        return CommonResult.success(allUser);
    }

    //修改
    @PostMapping("/updateUser")
    public CommonResult updateUser(@RequestBody UserUpdateForm form) {
        Boolean res = userService.updateUser(form);
        return res?CommonResult.success(MessageConstants.USER_UPDATED_SUCCESSFULLY):
                CommonResult.error(ReturnCode.FAIL.getCode(), MessageConstants.USER_NOT_FOUND);
    }

    //删除
    @DeleteMapping("/deleteUser")
    public CommonResult deleteUser(@RequestBody List<String> userIds) {
        // 1. 参数校验
        if (userIds == null || userIds.isEmpty()) {
            return CommonResult.error("请提供要删除的用户ID列表");
        }

        // 2. 执行批量删除
        try {
            int deletedCount = userService.deleteByIds(userIds);
            if (deletedCount > 0) {
                return CommonResult.success("成功删除 " + deletedCount + " 个用户");
            } else {
                return CommonResult.error("未找到匹配的用户或删除失败");
            }
        } catch (Exception e) {
            return CommonResult.error("删除用户时出错: " + e.getMessage());
        }
    }

    // 邮箱密码重置
    @PostMapping("/resetPassword")
    public CommonResult resetPassword(@RequestBody UserRePassForm form) throws Exception {
//        查找用户是否存在
        UserInfo user = userService.findByUsername(form.getUsername());
        if (user == null) {
            return CommonResult.error(ReturnCode.FAIL.getCode(), MessageConstants.USER_NOT_FOUND);
        }
//        邮箱不能为空 和格式校验
        if (StringUtils.isEmpty(form.getEmail())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(), "邮箱不能为空");
        }
        if (!UserValidationUtil.validateEmail(form.getEmail())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(), "邮箱格式不正确");
        }
        if (!user.getEmail().equals(form.getEmail())){
            return CommonResult.error(ReturnCode.FAIL.getCode(), "邮箱不匹配");
        }
        String password = PasswordGenerator.generatePassword();
        Context context = new Context();
        context.setVariable("username", form.getUsername());
        context.setVariable("password", password);
        String content = templateEngine.process("template.html", context);
        emailService.sendHtml(emailConfig.getSenderEmail(), form.getEmail(), "密码重置通知", content);
        user.setPassword(passwordEncoder.encode(password));
        Boolean b = userService.resetPassword(user);
        return b ? CommonResult.success("重置密码成功") : CommonResult.error(ReturnCode.FAIL.getCode(), "重置密码失败");
    }

    @GetMapping("/getCurrentUser")
    public CommonResult getCurrentUser() {
        AuthUser user = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserContext userContext = new UserContext();
        userContext.setUserId(user.getUserId());
        userContext.setUsername(user.getUsername());
        userContext.setRoleCode(user.getRole());
        userContext.setEmail(user.getEmail());
        userContext.setAuthority(Collections.singletonList(user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()).toString()));
        HashSet<String> code = permissionDao.selectCodeList(user.getRole());
        userContext.setPermissionCode(code);
        return CommonResult.success(userContext);
    }


}
